package cn.fancy.sdk.openwebview;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import cn.fancy.sdk.FileUtils;
import cn.fancy.sdk.common.utils.Logger;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;

public class OpenWebView extends Activity implements OnClickListener {
	private static String URL = "url";
	private static String RequestString = "source";
	private static Context staticCon;
	private ValueCallback<Uri> mUploadMessage;
	private final static int FILECHOOSER_RESULTCODE = 1;

	private Button closeBtn, rushBtn, backwardBtn, forwardBtn;

	private Handler uhandle;
	private boolean canDestroy = false;

	private boolean firenter = true;

	public static Context gameContext = null;
	WebView webView;
	String url;
	String requestSource = "";

	private ImageView defaultshow;
	ClipboardManager clisign;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(ResUtil.getLayoutId(OpenWebView.this,
				"com_web_layview"));

		int incode = ResUtil.getAnimId(staticCon, "float_pushin");
		overridePendingTransition(incode, 0);

		defaultshow = (ImageView) this.findViewById(ResUtil.getId(
				OpenWebView.this, "web_default_show"));
		closeBtn = (Button) this.findViewById(ResUtil.getId(OpenWebView.this,
				"close_web_btn"));
		rushBtn = (Button) this.findViewById(ResUtil.getId(OpenWebView.this,
				"rush_web_btn"));
		backwardBtn = (Button) this.findViewById(ResUtil.getId(OpenWebView.this,
				"backward_web_btn"));
		forwardBtn = (Button) this.findViewById(ResUtil.getId(OpenWebView.this,
				"forward_web_btn"));

		closeBtn.setOnClickListener(this);
		rushBtn.setOnClickListener(this);
		backwardBtn.setOnClickListener(this);
		forwardBtn.setOnClickListener(this);

		webView = (WebView) this.findViewById(ResUtil.getId(OpenWebView.this,
				"web_show_view"));

		Intent intent = this.getIntent();

		url = intent.getStringExtra(URL);
		requestSource = intent.getStringExtra(RequestString);
		initView();
		uhandle = new Handler();

		clisign = (ClipboardManager) staticCon
				.getSystemService(Context.CLIPBOARD_SERVICE);

	}

	public Bitmap getBitmap(String path) throws IOException {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == 200) {
			InputStream inputStream = conn.getInputStream();
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			return bitmap;
		}
		return null;
	}

	public void initView() {		
		webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		webView.getSettings().setAppCacheEnabled(false);
		webView.getSettings().setDatabaseEnabled(false);
		webView.getSettings().setDomStorageEnabled(false);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setDefaultTextEncodingName("UTF-8");
		webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		webView.setDownloadListener(new QCDownloadListener());

		// 设置缓存，减少打开悬浮的loading时间
		webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
		String appCacheDir = this.getApplicationContext()
				.getDir("guild_cache", Context.MODE_PRIVATE).getPath();
		webView.getSettings().setAppCachePath(appCacheDir);
		webView.getSettings().setAllowFileAccess(true);
		webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

		String finalUrl = url;
		if (requestSource != null && !requestSource.equals("")) {
			finalUrl = url + "?" + requestSource;
		}

		// 加载页面，假如要点击小红点自动跳到活动更新页，应修改url
		webView.loadUrl(finalUrl);
		webView.setWebViewClient(new WebViewClient() {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				String allurl = url;
				if (allurl.indexOf("itunes.apple.com") != -1) {
					view.stopLoading();
					return true;
				}

				return super.shouldOverrideUrlLoading(view, url);

			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				canDestroy = false;
				//Toast.makeText(staticCon, "开始加载", Toast.LENGTH_LONG).show();
				String allurl = url;
				if (allurl.indexOf("itunes.apple.com") != -1) {
					return;
				}

				super.onPageStarted(view, url, favicon);
				if (firenter) {

					firenter = false;
					new Thread() {
						public void run() {
							try {
								Thread.sleep(5000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							uhandle.post(hidedialogR);
						}
					}.start();
				}
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				//Toast.makeText(staticCon, "加载结束", Toast.LENGTH_LONG).show();
				super.onPageFinished(view, url);
				canDestroy = true;
				defaultshow.setVisibility(View.GONE);
				webView.loadUrl("javascript:function closeFloat(){Cfloatwindow.finish();}");
				webView.loadUrl("javascript:function changeUser(){Cfloatwindow.changeuser();}");
				webView.loadUrl("javascript:function contactQQ(qqnumber){Cfloatwindow.openmqq(qqnumber);}");
				webView.loadUrl("javascript:function contactmobile(number){Cfloatwindow.contactmobile(number);}");
				webView.loadUrl("javascript:function HiddenFloatWin(){Cfloatwindow.hiddenfloatwindow();}");
				webView.loadUrl("javascript:function DownLoadFileToC(downurl,filetype){Cfloatwindow.downloadfile(downurl,filetype);}");
				webView.loadUrl("javascript:function ResetUserPaasword(username,password){Cfloatwindow.resetpassword(username,password);}");
				webView.loadUrl("javascript:function FloatBindMobile(username){Cfloatwindow.BindMobile(username);}");

				// 增加公用接口，跳转到浏览器
				webView.loadUrl("javascript:function openBrowserWithUrl(url){Cfloatwindow.openBrowser(url);}");
				// 复制礼包吗
				webView.loadUrl("javascript:function copyPackageNumber(number){Cfloatwindow.copyPackageNumber(number);}");

				// 请求红点时间、开关红点请求
				webView.loadUrl("javascript:function spaceRedPoint(signs){Cfloatwindow.spaceRedPoint(signs);}");
				webView.loadUrl("javascript:function switchRedPoint(signs){Cfloatwindow.switchRedPoint(signs);}");
			}
		});

		webView.setWebChromeClient(new WebChromeClient() {

			// For Android 3.0+
			public void openFileChooser(ValueCallback<Uri> uploadMsg) {
				Log.i("UPFILE", "in openFile Uri Callback");
				if (mUploadMessage != null) {
					mUploadMessage.onReceiveValue(null);
				}
				mUploadMessage = uploadMsg;
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				i.setType("*/*");
				startActivityForResult(Intent.createChooser(i, "File Chooser"),
						FILECHOOSER_RESULTCODE);
			}

			// For Android 3.0+
			public void openFileChooser(ValueCallback uploadMsg,
					String acceptType) {
				Log.i("UPFILE", "in openFile Uri Callback has accept Type"
						+ acceptType);
				if (mUploadMessage != null) {
					mUploadMessage.onReceiveValue(null);
				}
				mUploadMessage = uploadMsg;
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				String type = TextUtils.isEmpty(acceptType) ? "*/*"
						: acceptType;
				i.setType(type);
				startActivityForResult(Intent.createChooser(i, "File Chooser"),
						FILECHOOSER_RESULTCODE);
			}

			// For Android 4.1
			public void openFileChooser(ValueCallback<Uri> uploadMsg,
					String acceptType, String capture) {
				Log.i("UPFILE", "in openFile Uri Callback has accept Type"
						+ acceptType + "has capture" + capture);
				if (mUploadMessage != null) {
					mUploadMessage.onReceiveValue(null);
				}
				mUploadMessage = uploadMsg;
				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
				i.addCategory(Intent.CATEGORY_OPENABLE);
				String type = TextUtils.isEmpty(acceptType) ? "*/*"
						: acceptType;
				i.setType(type);
				startActivityForResult(Intent.createChooser(i, "File Chooser"),
						FILECHOOSER_RESULTCODE);
			}
			// Android 5.0+

		});

	}

	private class QCDownloadListener implements DownloadListener {

		@Override
		public void onDownloadStart(String url, String userAgent,
				String contentDisposition, String mimetype,

				long contentLength) {

			// 参数1 下载链接 参数2 文件存放名字 参数3 下载提示
			// 创建下载任务,downloadUrl就是下载链接
			DownloadManager.Request request = new DownloadManager.Request(
					Uri.parse(url));
			// 设置允许下载的网络环境
			request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
					| DownloadManager.Request.NETWORK_MOBILE);
			// 在Notification显示下载进度
			request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE
					| DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

			String filename = url.substring(url.lastIndexOf("/") + 1);
			// 指定下载路径和下载文件名
			request.setDestinationInExternalPublicDir("/download/", "");
			// 显示下载界面
			request.setVisibleInDownloadsUi(true);
			request.setTitle("游戏下载中");
			DownloadManager downloadManager = (DownloadManager) staticCon
					.getSystemService(Context.DOWNLOAD_SERVICE);
			// 将下载任务加入下载队列，否则不会进行下载
			long fileid = downloadManager.enqueue(request);

			if (url.endsWith(".apk")) {
			}
			Toast.makeText(staticCon, "已加入下载，请注意查看", Toast.LENGTH_SHORT).show();
		}

	}

	Runnable hidedialogR = new Runnable() {
		@Override
		public void run() {
			canDestroy = true;
			// dialog.setCancelable(true);
		}

	};

	@Override
	public void onBackPressed() {
		if (!NetworkImpl.isNetworkConnected(staticCon) || canDestroy) {
			webView.destroy();
			this.finish();
			/* 返回键 */
		}
	}

	public static void start(Context context, String url,
			Map<String, String> params) {

		String reusetString = getMaptoUrlR(params);
		Intent intent = new Intent();
		staticCon = context;
		intent.putExtra(URL, url);
		intent.putExtra(RequestString, reusetString);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setClass(context, OpenWebView.class);
		try {
			context.startActivity(intent);
		} catch (Exception e) {
			Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
		}

	}

	private static String getMaptoUrlR(Map<String, String> params) {
		String finalString = "";
		if (params == null) {
			return finalString;
		}

		try {
			StringBuffer buffer = new StringBuffer();
			for (Iterator<?> iter = params.entrySet().iterator(); iter
					.hasNext();) {
				Entry<?, ?> element = (Entry<?, ?>) iter.next();
				if (element.getValue() == null || element.getKey() == null) {
					Logger.e("tag", "elenment is null");
					continue;
				}
				buffer.append(element.getKey().toString());
				buffer.append("=");
				buffer.append(element.getValue().toString());
				buffer.append("&");
			}

			if (buffer.length() > 0) {
				buffer = buffer.deleteCharAt(buffer.length() - 1);
			}
			if (buffer != null) {
				finalString = buffer.toString();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return finalString;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == FILECHOOSER_RESULTCODE) {
			if (null == mUploadMessage)
				return;
			Uri result = data == null || resultCode != RESULT_OK ? null : data
					.getData();
			if (result == null) {
				mUploadMessage.onReceiveValue(null);
				mUploadMessage = null;
				return;
			}
			Log.i("UPFILE", "onActivityResult" + result.toString());
			String path = FileUtils.getPath(this, result);
			if (TextUtils.isEmpty(path)) {
				mUploadMessage.onReceiveValue(null);
				mUploadMessage = null;
				return;
			}
			Uri uri = Uri.fromFile(new File(path));
			Log.i("UPFILE",
					"onActivityResult after parser uri:" + uri.toString());
			mUploadMessage.onReceiveValue(uri);
			mUploadMessage = null;
		}
	}

	@Override
	public void onClick(View v) {

		int vid = v.getId();

		if (!canDestroy) {
			return;
		}

		if (vid == ResUtil.getId(this.getBaseContext(), "close_web_btn")) {
			webView.destroy();
			this.finish();
		} else if (vid == ResUtil.getId(this.getBaseContext(), "rush_web_btn")) {
			webView.reload();
		} else if (vid == ResUtil.getId(this.getBaseContext(),
				"backward_web_btn")) {
			webView.goBack();
		} else if (vid == ResUtil.getId(this.getBaseContext(),
				"forward_web_btn")) {
			webView.goForward();
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void finish() {
		super.finish();
	}

}
